package com.mx.base.language.script.remote

import com.mx.base.language.script.XmlHelper
import java.io.File


/**
 * @author: xiao.ma
 * Date: 2022/2/8 17:17
 * Desc:
 */

class PushScript {

    private val resPath = "src/main/res"
    private var baseLanguage = "values-zh-rCN"
    private fun fileFilter(file: File): Boolean {
        return file.isDirectory
                && !file.name.startsWith(".")
                && File(
            file.absolutePath,
            "$resPath/$baseLanguage/strings.xml"
        ).run {
            exists() && isFile
        }
    }

    fun loadProjectLanguage(projectPath: String): ProjectLanguage {
        val modules = File(projectPath).listFiles { file -> fileFilter(file) } ?: arrayOf()
        val languages = modules.map { loadModuleLanguage(it) }.toMutableList()
        return ProjectLanguage("", languages)
    }

    private fun loadModuleLanguage(moduleFile: File): ModuleLanguage {
        val languages = File(moduleFile, resPath).listFiles { file ->
            file.isDirectory && file.name.startsWith("values")
        } ?: arrayOf()

        val languageMaps = languages.map {
            Language(it.name, XmlHelper.readStringXml(File(it, "strings.xml")))
        }.toMutableList()

        return ModuleLanguage(moduleFile.name, languageMaps)
    }

    private fun uploadModuleLanguage(moduleFile: File) {
        val languages = File(moduleFile, resPath).listFiles { file ->
            file.isDirectory && file.name.startsWith("values")
        } ?: arrayOf()
        println("--->languages=${languages.size}")
        languages.forEach {
            uploadLanguage(
                moduleFile.name,
                it.name,
                XmlHelper.readStringXml(File(it, "strings.xml"))
            )
        }

    }

    fun run() {
        val modules = File("./").listFiles { file ->
            fileFilter(file)
        } ?: arrayOf()
        println("--->modules=${modules.size}")
        modules.forEach {
            uploadModuleLanguage(it)
        }
    }


    private fun uploadLanguage(
        module: String,
        language: String,
        xmlMap: MutableMap<String, String>
    ) {

        println("--->正在上传$module--$language")
        val response = NetWork.instance.getApi(Api::class.java)
            .postLanguage(LanguageBean(691042222438887424, module, language, xmlMap))
            .execute()
        println("--->onResponse=${response.body()}")

    }
}

fun main() {

    PushScript().run()
}